package com.example.redislearning.controller;

import com.example.redislearning.dto.ApiResponse;
import com.example.redislearning.entity.Course;
import com.example.redislearning.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 课程管理控制器
 * 提供课程的CRUD操作、搜索、分类、排行榜等功能
 */
@RestController
@RequestMapping("/api/courses")
public class CourseController {

    @Autowired
    private CourseService courseService;

    /**
     * 创建课程
     */
    @PostMapping
    public ApiResponse<Course> createCourse(@RequestBody Course course) {
        try {
            Course createdCourse = courseService.createCourse(course);
            return ApiResponse.success("课程创建成功", createdCourse);
        } catch (Exception e) {
            return ApiResponse.error(500, "课程创建失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取课程详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Course> getCourseById(@PathVariable Integer id) {
        try {
            Course course = courseService.getCourseById(id);
            if (course != null) {
                return ApiResponse.success("课程获取成功", course);
            } else {
                return ApiResponse.error(404, "课程不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "获取课程失败: " + e.getMessage());
        }
    }

    /**
     * 更新课程信息
     */
    @PutMapping("/{id}")
    public ApiResponse<Course> updateCourse(@PathVariable Integer id, @RequestBody Course course) {
        try {
            course.setId(id);
            Course updatedCourse = courseService.updateCourse(course);
            if (updatedCourse != null) {
                return ApiResponse.success("课程更新成功", updatedCourse);
            } else {
                return ApiResponse.error(404, "课程不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "更新课程失败: " + e.getMessage());
        }
    }

    /**
     * 删除课程（软删除）
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteCourse(@PathVariable Integer id) {
        try {
            boolean deleted = courseService.deleteCourse(id);
            if (deleted) {
                return ApiResponse.success("课程删除成功", null);
            } else {
                return ApiResponse.error(404, "课程不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error(500, "删除课程失败: " + e.getMessage());
        }
    }

    /**
     * 分页获取课程列表
     */
    @GetMapping
    public ApiResponse<Page<Course>> getCourseList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Course> courses = courseService.getCourseList(pageable);
            return ApiResponse.success("课程列表获取成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取课程列表失败: " + e.getMessage());
        }
    }


    /**
     * 根据分类获取课程
     */
    @GetMapping("/category/{categoryId}")
    public ApiResponse<Page<Course>> getCoursesByCategory(
            @PathVariable Integer categoryId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Course> courses = courseService.getCoursesByCategory(categoryId, pageable);
            return ApiResponse.success("分类课程获取成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取分类课程失败: " + e.getMessage());
        }
    }

    /**
     * 搜索课程
     */
    @GetMapping("/search")
    public ApiResponse<Page<Course>> searchCourses(
            @RequestParam String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String difficulty,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<Course> courses = courseService.searchCourses(keyword, category, difficulty, pageable);
            return ApiResponse.success("搜索课程成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "搜索课程失败: " + e.getMessage());
        }
    }

    /**
     * 获取热销课程排行榜
     */
    @GetMapping("/ranking/sales")
    public ApiResponse<List<Course>> getSalesRanking(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Course> courses = courseService.getTopSellingCourses(limit);
            return ApiResponse.success("热销排行榜获取成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取热销排行榜失败: " + e.getMessage());
        }
    }

    /**
     * 获取高分课程排行榜
     */
    @GetMapping("/ranking/rating")
    public ApiResponse<List<Course>> getRatingRanking(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Course> courses = courseService.getTopRatedCourses(limit);
            return ApiResponse.success("高分排行榜获取成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取高分排行榜失败: " + e.getMessage());
        }
    }

    /**
     * 获取热门浏览课程排行榜
     */
    @GetMapping("/ranking/views")
    public ApiResponse<List<Course>> getViewRanking(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Course> courses = courseService.getMostViewedCourses(limit);
            return ApiResponse.success("浏览排行榜获取成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取浏览排行榜失败: " + e.getMessage());
        }
    }

    /**
     * 获取最新课程
     */
    @GetMapping("/latest")
    public ApiResponse<List<Course>> getLatestCourses(@RequestParam(defaultValue = "10") int limit) {
        try {
            List<Course> courses = courseService.getLatestCourses(limit);
            return ApiResponse.success("最新课程获取成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取最新课程失败: " + e.getMessage());
        }
    }

    /**
     * 获取免费课程
     */
    @GetMapping("/free")
    public ApiResponse<List<Course>> getFreeCourses(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<Course> courses = courseService.getFreeCourses(page, size);
            return ApiResponse.success("免费课程获取成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取免费课程失败: " + e.getMessage());
        }
    }

    /**
     * 根据价格区间获取课程
     */
    @GetMapping("/price-range")
    public ApiResponse<List<Course>> getCoursesByPriceRange(
            @RequestParam Double minPrice,
            @RequestParam Double maxPrice,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<Course> courses = courseService.getCoursesByPriceRange(minPrice, maxPrice, page, size);
            return ApiResponse.success("价格区间课程获取成功", courses);
        } catch (Exception e) {
            return ApiResponse.error(500, "获取价格区间课程失败: " + e.getMessage());
        }
    }

    /**
     * 获取讲师的课程
     */
    //TODO 后面再加
//    @GetMapping("/instructor/{instructor}")
//    public ApiResponse<List<Course>> getCoursesByInstructor(
//            @PathVariable String instructor,
//            @RequestParam(defaultValue = "0") int page,
//            @RequestParam(defaultValue = "10") int size) {
//        try {
//            List<Course> courses = courseService.getCoursesByInstructor(instructor, page, size);
//            return ApiResponse.success("讲师课程获取成功", courses);
//        } catch (Exception e) {
//            return ApiResponse.error(500, "获取讲师课程失败: " + e.getMessage());
//        }
//    }

    /**
     * 增加课程浏览量
     */
    @PostMapping("/{id}/views")
    public ApiResponse<Void> incrementViewCount(@PathVariable Integer id) {
        try {
            courseService.incrementViews(id);
            return ApiResponse.success("浏览量增加成功", null);
        } catch (Exception e) {
            return ApiResponse.error(500, "增加浏览量失败: " + e.getMessage());
        }
    }

    /**
     * 增加课程销量
     */
    @PostMapping("/{id}/sales")
    public ApiResponse<Void> incrementSalesCount(@PathVariable Integer id, @RequestParam(defaultValue = "1") int increment) {
        try {
            courseService.incrementCourseSales(id, increment);
            return ApiResponse.success("销量增加成功", null);
        } catch (Exception e) {
            return ApiResponse.error(500, "增加销量失败: " + e.getMessage());
        }
    }

    /**
     * 更新课程评分
     */
    @PostMapping("/{id}/rating")
    public ApiResponse<Void> updateRating(@PathVariable Integer id, @RequestParam Double rating) {
        try {
            courseService.updateRating(id, rating, 1);
            return ApiResponse.success("评分更新成功", null);
        } catch (Exception e) {
            return ApiResponse.error(500, "更新评分失败: " + e.getMessage());
        }
    }
}